var express = require('express');
var router = express.Router();
//引入 crypto模块和user.js用户模型文件
var crypto = require('crypto');
var User = require('../models/user');
var Post = require('../models/post');
var Stra = require('../models/strategy');
var Comment=require('../models/comments');
var Concern=require('../models/concern');
var Collect=require('../models/collect');
//var Concern=require('../models/good');

/*生成路由用来捕获主页的get请求 ,导出这个路由并在app.js中通过app.use('/',routes)加载.
当访问主页的时候 会调用res.render('index', { title: 'Express' }); 渲染ejs模板并显示到浏览器中*/

/*----------------------------------------------------4个导航栏*/

//首页
router.get('/', function(req, res, next) {
	res.render('index3', {
		title: 'Express',
		user: req.session.user,
		success: req.flash('success').toString(),
		error: req.flash('error').toString()
	});
});
//目的地页面
router.get('/totermini', function(req, res, next) {
	Stra.getAlls(null, function(err, stras) {
		if(err) {
			stras = [];
		}
	Post.getAll(null, function(err, posts) {
		if(err) {
			posts = [];
		}
		res.render('termini', {
			title: '我是目的地页面',
			posts: posts,
			stras:stras,
			user: req.session.user,
			success: req.flash('success').toString(),
			error: req.flash('error').toString()
		});
	});
	});
	
});
//游记页面
router.get('/totravel_notes', function(req, res) {
	Post.getFive(1, function(err, posts) {
		if(err) {
			posts = [];
		}
		res.render('travel_notes', {
			title: '我是游记页面',
			posts: posts,
			user: req.session.user,
			success: req.flash('success').toString(),
			error: req.flash('error').toString()
		});
	});
});
//瀑布流分页
router.post('/waterfall',function(req,res){
	var newpage=req.body.nowpage;
	//console.log(newpage);
	Post.getFive(newpage,function(err,posts){
		console.log('post数据量：'+posts.length);
		req.flash('success','成功');
		return res.send(posts);
	})
})

//ajax实现攻略查询
router.get('/tostra',function(req,res){
	Stra.getAlls(null,function(err,stras){
		if(err){
			stras=[];
		}
	res.render('stras2',{
		user:req.session.user,
		stras:stras
	});
	});
});
router.post('/poststra',function(req,res){
	
	console.log('地点'+req.body.areas);
	console.log('时间'+req.body.time_days);
	Stra.searchname(req.body.areas,req.body.time_days,function(err,stras){
		if(err) {
			req.flash('error', err);
			return res.redirect('back');
		//	console.log("搜索攻略结果"+stras);
			
		}
		//console.log(stras);
		req.flash('success','成功');

		return res.send(stras);
		
	})
	
	
});
//社区页面
router.get('/tocommunity', function(req, res) {
		Post.getAll(req.session.user.name, function(err, posts) {
			if(err) {
				req.flash('error', err);
				return res.redirect('/');
			}
			res.render('community', {
				title: "我是社区页面",
				posts: posts,
				user: req.session.user,
				success: req.flash('success').toString(),
				error: req.flash('error').toString()
			});
	});
});


/*----------------------------------------------------游记功能模块*/

//发布游记页面
router.get('/to_pub_tra', checklogin);
router.get('/to_pub_tra', function(req, res, next) {
	res.render('pub_notes', {
		title: '我是发表游记页面',
		user: req.session.user,
		success: req.flash('success').toString(),
		error: req.flash('error').toString()
	});
});
//发表游记功能
router.post('/dopub', function(req, res) {
	var currentUser = req.session.user,
		post = new Post(currentUser.name,currentUser.head, req.body.title, req.body.area, req.body.article);
	//console.log("我是内容"+req.body.article);
	post.save(function(err) {
		if(err) {
			req.flash('error', err);
			return res.redirect('/to_pub_tra');
		}
		//console.log(req.body.area);
		req.flash('success', '发表成功');
		res.redirect('/totravel_notes');
	});
});

//游记页面显示排序
//时间排序
router.get('/archive',function(req,res){
	Post.getArchive(function(err,posts){
		if(err){
			req.flash('error',err);
			return res.redirect('/');
		}
		res.render('travel_notes',{
			title:"存档",
			posts:posts,
			user:req.session.user,
			success:req.flash('success').toString(),
			error:req.flash('error').toString
		});
	});
});
//热度排序
router.get('/gethot',function(req,res){
	Post.getHot(function(err,posts){
		if(err){
			req.flash('error',err);
			return res.redirect('/');
		}
		res.render('travel_notes',{
			title:"存档",
			posts:posts,
			user:req.session.user,
			success:req.flash('success').toString(),
			error:req.flash('error').toString
		});
	});
});
//查看游记全文详情
router.get('/u/:name/:day/:title/:area', function(req, res) {
	Concern.search(req.session.user.name,function(err,concerns){
		if(err){
			req.flash('error',err);
			return res.redirect('/');
		}
		console.log("好友数据1"+concerns);
	Collect.search(req.session.user.name,function(err,collects){
		if(err){
			req.flash('error',err);
			return res.redirect('/');
		}
		console.log("收藏数据"+collects);
		
	Post.search(req.params.area,function(err,article){
		if(err){
			req.flash('error',err);
			return res.redirect('/');
		}
	User.getname(req.params.name, function(err, user) {
		//console.log("错5"+req.params.name);
		if(!user) {
			req.flash('error', '用户不存在');
			return res.redirect('/');
		}
	Post.getOne(req.params.name,req.params.day,req.params.title, function(err, posts) {
		if(err) {
			req.flash('error', err);
			return res.redirect('/');
		}
		//console.log("错6"+req.params.area);
		return res.render('articles', {
			title: req.params.title,
			post: posts,
			arts:article,
			concerns:concerns,
			collects:collects,
			areas:req.params.area,
			head:user.head,
			user: req.session.user,
			success: req.flash('success').toString(),
			error: req.flash('error').toString()
	});
	
	});
	});
});
});
});
});

//评论游记
router.post('/u/:name/:day/:title/:area', function(req, res) {
	console.log("来了");
	var date=new Date(),
		time=date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDay()+" "+date.getHours()+":"+(date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes());
		var comment={
			name:req.session.user.name,
			head:req.session.user.head,
			time:time,
			content:req.body.content
		};
		
		var newComment=new Comment(req.params.name,req.params.day,req.params.title,comment);
		newComment.save(function(err){
			if(err){
				req.flash('error',err);
				return res.redirect('back');
			}
			req.flash('success','成功');
			res.redirect('back');
		});
});
//编辑游记页面
router.get('/edit/:name/:day/:title', checklogin);
router.get('/edit/:name/:day/:title',function(req,res){
	var currentUser=req.session.user.name;
		
	
	Post.edit(currentUser,req.params.day,req.params.title,function(err,post){
		if(err){
			req.flash('error',err);
			return res.redirect('back');
		}
		res.render('edit',{
			title:"我是编辑页面",
			post:post,
			user:req.session.user,
			success:req.flash('success').toString(),
			error:req.flash('error').toString()
		});
		
	});
});
//编辑游记功能
router.post('/edit/:name/:day/:title/:area',function(req,res){
	var currentUser=req.session.user.name;
	
	Post.update(currentUser,req.params.day,req.params.title,req.body.article,function(err){
		var url=encodeURI('/u/'+req.params.name+'/'+req.params.day+'/'+req.params.title+'/'+req.params.area);
		if(err){
			req.flash('error',err);
			return res.redirect('back');
		}
		req.flash('success','修改成功');
		res.redirect(url);
		console.log('修改成功');
		//console.log(req.body.article);
	});
});
//删除游记功能
router.get('/remove/:name/:day/:title', checklogin);
router.get('/remove/:name/:day/:title',function(req,res){
	
	var currentUser=req.session.user.name;
	Post.remove(currentUser,req.params.day,req.params.title,function(err){
	
		if(err){
		req.flash('error',err);
		return res.redirect('back');
		console.log("不成功");
		}
		console.log("成功");
		req.flash('success','删除成功');
		res.redirect('back');
	});
});



/*--------------------------------------------------------图片上传*/
router.get('/upload', checklogin);
router.get('/upload', function(req, res) {
	res.render('#myModal', {
		title: '图片上传',
		user: req.session.user,
		head:'',
		success: req.flash('success').toString(),
		error: req.flash('error').toString()

	});
	
});
//上传图片
router.post('/upload', function(req, res, next) {
	console.log("1111");
	var imgpath="upload_imgs/"+req.files.file1.name;
	console.log("图片："+imgpath);
	console.log("我不是："+req.session.user.name);
	User.update(req.session.user.name,imgpath,function(err){
		console.log("1000");
		if(err){
			req.flash('err','失败');
			return res.redirect('/topsn_page');
		}
	req.flash('success', '文件上传成功');
	//alert()
	 console.log(req.files.file1.originalname);
	 //console.log(req.files.originalname);
	//console.log("我是图片路径"+req.files);
	req.session.user.head=imgpath;
	return res.redirect('/topsn_page');
	});
	
});




/*------------------------------------------------------搜索功能*/
router.get('/search',function(req,res){
	Post.search(req.query.searchword,function(err,posts){
		if(err){
			req.flash('error',err);
			return res.redirect('/');
		}
		res.render('search',{
			title:req.query.searchword,
			posts:posts,
			user:req.session.user,
			success: req.flash('success').toString(),
			error: req.flash('error').toString()
		});
//		console.log(req.query.searchword);
//		console.log(posts);
	});
});


/*-------------------------------------------------------用户模块*/


//注册方法
router.post('/doregister', function(req, res) {
	var name = req.body.name,
		password = req.body.password,
		password1 = req.body.password1,
		telephone=req.body.telephone,
		email= req.body.email;
	
	//检验两次输入的密码是否一致
	if(name==""){
		req.flash('error', '用户名不能为空');
		return res.redirect('/toregister');
	}
	if(password==""){
		req.flash('error', '请输入密码');
		return res.redirect('/toregister');
	}
	if(password1==""){
		req.flash('error', '请输入确认密码');
		return res.redirect('/toregister');
	}
	if(email==""){
		req.flash('error', '请输入邮箱');
		return res.redirect('/toregister');
	}
	if(password1 != password) {
		req.flash('error', '两次输入的密码不一致');
		return res.redirect('/toregister');
	}
	//生成密码的md5值
	var md5 = crypto.createHash('md5'),
		password = md5.update(req.body.password).digest('hex');
			console.log('有毒00');
	var newUser = new User({
		name: req.body.name,
		head: 'upload_imgs/background.jpg',
		password: password,
		telephone: req.body.telephone,
		email: req.body.email
	});
			
			console.log(newUser);
	
	//检查用户名是否存在
	User.getname(newUser.name, function(err, user) {
			console.log('有毒0000');
		
		if(err) {
			req.flash('error', err);
			return res.redirect('/');
			
		}
		if(user) {
			req.flash('error', '用户名已存在');
			return res.redirect('/toregister');
			console.log('有毒2');
			
		}
		console.log('zhuce');
		//用户名不存在则新增用户 
		newUser.save(function(err, user) {
			if(err) {

				return res.redirect('/toregister');
				console.log("cuo");
			}
			console.log('我是正确的');
			req.session.user = user; //用户信息存入session
			req.flash('sussess', '注册成功');
			return res.redirect('/tologin');

			/*return res.render('/login',{title:'注册成功'});*/
			console.log("succ");
		});
	});
});
//注册页面
router.get('/toregister', function(req, res, next) {
	res.render('register', {
		title: '我是注册',
		user: req.session.user,
		success: req.flash('success').toString(),
		error: req.flash('error').toString()
	});
});
//登录页面
router.get('/tologin', function(req, res, next) {
	res.render('login', {
		title: '我是登录',
		user: req.session.user,
		success: req.flash('success').toString(),
		error: req.flash('error').toString()
	});
});
//登录方法
router.post('/dologin', function(req, res) {
	//生成密码的md5值
	var md5 = crypto.createHash('md5'),
		password = md5.update(req.body.password).digest('hex');

	//检测用户名是否存在
	User.getname(req.body.name, function(err, user) {
		if(!user) {
			req.flash('error', '用户不存在！');
			return res.redirect('/tologin');
		}
		if(user.password != password) {
			console.log(user.password);
			console.log(password);
			req.flash('error', '密码错误！');
			return res.redirect('/tologin');
		}
		req.session.user = user;
		req.flash('error', '登录成功！');
		return res.redirect('/');
	});

});

//关注好友
router.post('/toconcern/:name', function(req, res) {
		console.log(req.session.user.name);
		var newConcern=new Concern({
			name:req.session.user.name,
			concern:req.params.name
		});
		
	newConcern.save(function(err) {
		if(err) {
			req.flash('error', err);
			return res.redirect('back');
		}
		req.flash('success','成功');
	
		return res.send(newConcern);

		
	});
});
//收藏
router.post('/collect/:name', function(req, res) {
		console.log("成功0");
		console.log(req.session.user.name);
		console.log(req.params.name);
		var newCollect=new Collect({
			name:req.session.user.name,
			collect:req.params.name
		});
		console.log("成功1");
		
		newCollect.save(function(err) {
		if(err) {
			req.flash('error', err);
			return res.redirect('back');
		}
		req.flash('success','成功');
		return res.send(newCollect);
		console.log("成功2");
	});
});
//取消收藏
router.get('/delcollect/:name', checklogin);
router.get('/delcollect/:name',function(req,res){
	Collect.remove(req.params.name,function(err){
		if(err){
		req.flash('error',err);
		return res.redirect('back');
		console.log("不成功");
		}
		console.log("成功");
		req.flash('success','删除成功');
		res.redirect('back');
	})
})
//个人主页
router.get('/topsn_page', function(req, res) {
	Concern.search(req.session.user.name,function(err,concerns){
		if(err){
			req.flash('error',err);
			return res.redirect('/');
		}
		Collect.search(req.session.user.name,function(err,collects){
		if(err){
			req.flash('error',err);
			return res.redirect('/');
		}
		console.log("收藏数据"+collects);
		Post.getAll(req.session.user.name, function(err, posts) {
			if(err) {
				req.flash('error', err);
				return res.redirect('/');
			}
			res.render('personal_page', {
				title: req.session.user.name,
				posts: posts,
				concerns:concerns,
				collects:collects,
				user: req.session.user,
				success: req.flash('success').toString(),
				error: req.flash('error').toString()
			});
			console.log(concerns);
			});
	});
	});
});

//查看用户信息
router.get('/u/:name', function(req, res) {
Concern.search(req.session.user.name,function(err,concerns){
		if(err){
			req.flash('error',err);
			return res.redirect('/');
		}
	User.getname(req.params.name, function(err, user) {
		
		if(!user) {
			req.flash('error', '用户不存在');
			return res.redirect('/');
		}

		Post.getAll(user.name, function(err, posts) {
			if(err) {
				req.flash('error', err);
				return res.redirect('/');
			}
			
			res.render('hispage', {
				title: user.name,
				head:user.head,
				posts: posts,
				concerns:concerns,
				user: req.session.user,
				success: req.params.name,
				error: req.flash('error').toString()
			});
		//console.log("头像"+head);
		});
	});
	});
});

//取消关注
router.get('/delconcern/:name', checklogin);
router.get('/delconcern/:name',function(req,res){
	Concern.remove(req.params.name,function(err){
		if(err){
		req.flash('error',err);
		return res.redirect('back');
		console.log("不成功");
		}
		console.log("成功");
		req.flash('success','删除成功');
		res.redirect('back');
	})
})

//修改个人资料
router.post('/change_info', function(req, res) {
	console.log(req.body.aaa);
	var sex=req.body.chan_sex,
		tele=req.body.chan_tele,
		email1=req.body.chan_ema,
		says=req.body.chan_says;
		console.log(sex);
	User.updateinfo(req.session.user.name,sex,tele,email1,says,function(err){
		if(err){
			req.flash('err','失败');
			return res.redirect('back');
		}
	req.flash('success', '修改成功');
	//alert()
	req.session.user.sex=req.body.chan_sex;
	req.session.user.telephone=req.body.chan_tele;
	req.session.user.email=req.body.chan_ema;
	req.session.user.says=req.body.chan_says;
	return res.redirect('/topsn_page');
	});
	
});

//注销
router.get('/dologout', function(req, res) {
	req.session.user = null;
	req.flash('success', '注销成功');

	res.redirect('/');
});


							/*检测登录与否*/
function checklogin(req, res, next) {
	if(!req.session.user) {
		req.flash('error', '未登录');
		return res.redirect('/tologin');
	}
	next();
};

function checkNotlogin(req, res, next) {
	if(!req.session.user) {
		req.flash('error', '已登录');
		return res.redirect('back');
	}
	next();
};

module.exports = router;